<?php
/**
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     function
 * Name:     pmvc_displayFormFieldErrors
 * Purpose:  renders form field errors
 * -------------------------------------------------------------
 */

use pmvc\template\smarty\SmartyUtil;
use pmvc\util\ReflectionUtil;

function smarty_function_pmvc_displayFormFieldErrors(Array $params, &$smarty) {
    
	// get errors
	$errors = isset($params["errors"])
		? $params["errors"] 
		: SmartyUtil::getTemplateVar($smarty, "formErrors");

	// none
    if (empty($errors) || count($errors)==0) {
        return SmartyUtil::returnOrAssign($smarty, $params, null);
    }

	// if it's the object, get the error array
	if (ReflectionUtil::isInstance($errors, 'pmvc\mvc\controller\FormErrors')) {
		$errors = $errors->get();
	}

    // get params
	$field 	= isset($params["field"]) 	? $params["field"] 	: null;
	$start 	= isset($params["start"]) 	? $params["start"] 	: "<ul class=\"errors field\">";
	$before = isset($params["before"]) 	? $params["before"] : "<li>";
	$after 	= isset($params["after"]) 	? $params["after"] 	: "</li>";
	$end 	= isset($params["end"]) 	? $params["end"] 	: "</ul>";

	// bail if we don't have any field errors
	if (!isset($errors["fieldErrors"])) {
        return SmartyUtil::returnOrAssign($smarty, $params, null);
	}

	// pull the field errors
	$fieldErrors = $errors["fieldErrors"];

	// bail if we don't have errors for this field
	if (isset($field) && empty($fieldErrors[$field])) {
        return SmartyUtil::returnOrAssign($smarty, $params, null);
	}

	// render for all fields
	$ret = '';
	if (!isset($field)) {
		$ret = $start;
		foreach ($fieldErrors as $field => $errors) {
			foreach ($errors as $error) {
				$ret .= $before.$error.$after;
			}
		}
		$ret .= $end;

	// render for specific field
	} else {
		$ret = $start;
		foreach ($fieldErrors[$field] as $error) {
			$ret .= $before.$error.$after;
		}
		$ret .= $end;
	}

	// return
	return SmartyUtil::returnOrAssign($smarty, $params, $ret);
}

?>